package io.renren.msg.client;


import com.xiaoleilu.hutool.date.DateUtil;
import io.renren.msg.Const;
import io.renren.msg.HelloPacket;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.Node;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * Created by kun on 2017/5/2.
 */
public class HelloClientStarter {
    public static Node serverNode = new Node("127.0.0.1", Const.PORT);

    public static ClientAioHandler<Object, HelloPacket, Object> aioClientHandler = new HelloClientAioHandler();

    public static ClientAioListener<Object, HelloPacket, Object> aioListener = null;

    //重连设置,null不重连
    private static ReconnConf<Object, HelloPacket, Object> reconnConf = new ReconnConf<>(5000L);

    public static ClientGroupContext<Object, HelloPacket, Object> clientGroupContext = new ClientGroupContext<Object, HelloPacket, Object>(aioClientHandler, aioListener, null);

    public static AioClient<Object, HelloPacket, Object> aioClient = null;
    public static ClientChannelContext<Object, HelloPacket, Object> clientChannelContext = null;

    public static void main(String args[]) throws Exception {
        aioClient = new AioClient<>(clientGroupContext);
        clientChannelContext = aioClient.connect(serverNode);
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入内容:");
        String line=null;
        while (true){
            line=scanner.nextLine();
            if (line.equals("bye")){
                break;
            }
            System.out.println("客户端在"+ DateUtil.now()+"说:"+line);
            send(line);
        }
    }

    private static void send(String content) {
        HelloPacket packet = new HelloPacket();
        try {
            packet.setBody(content.getBytes(HelloPacket.CHARSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Aio.send(clientChannelContext, packet);
    }

}
